package com.fast.cron.db.service;

import com.fast.cron.db.RowMapper;
import com.fast.cron.db.dao.AbstractDao;
import com.fast.cron.db.dao.JobDao;
import com.fast.cron.db.entry.Job;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Leo Jie
 * @date: 2018-10-02 21:33
 * @version: v1.0
 */
public class JobService extends AbstractDao implements JobDao {
    @Override
    public long addJob(Job job) throws SQLException {
        String sql = "insert into fast_cron_job(job_name,job_detail,job_command," +
                "created_user,created,last_update_time,time_out,retry_times)" +
                "values(?,?,?,?,?,?,?,?)";
        return insert(sql, job.getJobName(), job.getJobDetail(), job.getJobCommand(),
                job.getCreatedUser(), job.getCreated(), job.getLastUpdateTime(),
                job.getTimeOut(), job.getRetryTimes());
    }

    @Override
    public int removeJob(int jobId) throws SQLException {
        String sql = "update fast_cron_job set `status` = -2 where job_id = ?";
        return update(sql, jobId);
    }

    @Override
    public Job findOneJobById(int jobId) throws SQLException {
        String sql = "select job_id,job_name,job_detail,job_command," +
                "created_user,created,last_update_time,time_out," +
                "retry_times,`status` from fast_cron_job where job_id = ?";
        return queryOne(Job.class, sql, new JobRowMapper().rowMapperMap(), jobId);
    }

    @Override
    public List<Job> findJobListByUser(String username) throws SQLException {
        String sql = "select job_id,job_name,job_detail,job_command," +
                "created_user,created,last_update_time,time_out," +
                "retry_times,`status` from fast_cron_job where created_user = ?";
        return query(Job.class, sql, new JobRowMapper().rowMapperMap(), username);
    }

    private class JobRowMapper implements RowMapper {
        @Override
        public Map rowMapperMap() {
            Map<String, String> rowMap = new HashMap<>(8);
            rowMap.put("job_id", "jobId");
            rowMap.put("job_name", "jobName");
            rowMap.put("job_detail", "jobDetail");
            rowMap.put("job_command", "jobCommand");
            rowMap.put("created_user", "createdUser");
            rowMap.put("last_update_time", "lastUpdateTime");
            rowMap.put("time_out", "timeOut");
            rowMap.put("retry_times", "retryTimes");
            return rowMap;
        }
    }
}